package service

import (
	"server/global"
	"server/plugin/mall/model"
	"server/plugin/mall/model/request"
)

var A轮播 = new(lunbo)

type lunbo struct{}

// CreateA轮播 创建轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) CreateA轮播(lunbo *model.A轮播) (err error) {
	err = global.GVA_DB.Create(lunbo).Error
	return err
}

// DeleteA轮播 删除轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) DeleteA轮播(ID string) (err error) {
	err = global.GVA_DB.Delete(&model.A轮播{}, "id = ?", ID).Error
	return err
}

// DeleteA轮播ByIds 批量删除轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) DeleteA轮播ByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]model.A轮播{}, "id in ?", IDs).Error
	return err
}

// UpdateA轮播 更新轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) UpdateA轮播(lunbo model.A轮播) (err error) {
	// err = global.GVA_DB.Model(&model.A轮播{}).Where("id = ?", lunbo.ID).Updates(&lunbo).Error
	err = global.GVA_DB.Model(&lunbo).Where("id = ?", lunbo.ID).Updates(lunbo).Error
	// 通过反射获取传入参数的类型信息
	// value := reflect.ValueOf(lunbo)
	// if value.Kind() == reflect.Pointer {
	// 	value = value.Elem()
	// }
	// modelType := value.Type()
	// fmt.Printf("modelType 👉 %+v\n", modelType)
	// 检查结构体中是否存在名为ID的字段，若不存在则返回错误
	// idField, ok := modelType.FieldByName("ID")
	// if !ok {
	// 	return fmt.Errorf("传入的结构体类型 %s 中不存在名为ID的字段", modelType.Name())
	// }

	// 使用获取到的类型信息构建更新语句
	// modelInstance := value.Interface()
	// fmt.Printf("modelInstance 👉 %+v\n", modelInstance)
	// id值 := value.FieldByName("ID").Interface()
	// fmt.Printf("id值 👉 %+v\n", id值)
	// err = global.GVA_DB.Model(modelInstance).Where("id =?", id值).Updates(&lunbo).Error
	// fmt.Printf("lunbo 👉 %+v\n", lunbo)
	return err
}

// GetA轮播 根据ID获取轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) GetA轮播(ID string) (lunbo model.A轮播, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&lunbo).Error
	return
}

// GetA轮播InfoList 分页获取轮播记录
// Author [yourname](https://github.com/yourname)
func (s *lunbo) GetA轮播InfoList(info request.A轮播Search) (list []model.A轮播, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&model.A轮播{})
	var lunbos []model.A轮播
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&lunbos).Error
	return lunbos, total, err
}

func (s *lunbo) GetA轮播Public() {

}
